package com.solution;

/**
 * 783. 二叉搜索树节点最小距离
 * 给你一个二叉搜索树的根节点 root ，返回 树中任意两不同节点值之间的最小差值 。
 *
 * 示例 1：
 * 输入：root = [4,2,6,1,3]
 * 输出：1
 *
 * 示例 2：
 * 输入：root = [1,0,48,null,null,12,49]
 * 输出：1
 * @author LiYongKui
 * @version 1.0
 * @date 2021/4/13 14:06
 */
public class Solution0783 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static int minDiffInBST(TreeNode root) {
        int[] rs = {Integer.MAX_VALUE,-1};
        dfs(root,rs);
        return rs[0];
    }

    private static void dfs(TreeNode root, int[] rs) {
        if(root == null){
            return;
        }
        dfs(root.left,rs);
        if(rs[1] != -1){
            rs[0] = Math.min(root.val - rs[1],rs[0]);
        }
        rs[1] = root.val;
        dfs(root.right,rs);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4, new TreeNode(2, new TreeNode(1), new TreeNode(3)), new TreeNode(6));
        minDiffInBST(root);
    }
}
